/**
*  
* @Function 批量核查详情Controller 
* @ProjectName credit-data-platform 
* @PackageName com.py.credit.controller    
* @FileName BatchReportDetailController.java    
* @Date 2018年10月19日下午4:40:44
* @Author Min DongXv
* @Copyright (c) 2018, 金电联行 All Rights Reserved.   
*   
*/
package com.py.credit.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.MessageConstants;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.BatchReportDetailFieldsEnum;
import com.py.credit.service.BatchReportDetailService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * 
 * @Function 批量核查详情Controller
 * @ClassName BatchReportDetailController
 * @Date 2018年10月19日 下午4:40:44
 * @Author Min DongXv
 * 
 */
@RestController
@RequestMapping(value = "/batchDetail")
public class BatchReportDetailController extends BaseController {

	// 用户自定义列缓存key
	private static final String USER_DEFINED_COLUMN_KEY = "batchReportDetail";

	@Autowired
	private RemoteBaseService remoteBaseService;

	@Autowired
	private BatchReportDetailService batchReportDetailService;

	@Value("${absolutepath}")
	private String absolutepath;

	@Value("${pdfJsPath}")
	private String pdfJsPath;

	@Value("${googlePath}")
	private String googlePath;

	@Value("${pdfPagePath}")
	private String pdfPagePath;

	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		return new RestServiceResult<>(BatchReportDetailFieldsEnum.getOptionalColumns());
	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		return new RestServiceResult<>(BatchReportDetailFieldsEnum.getAdvancedConditionColumns());
	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg(MessageConstants.SYSTEM_ERROR);
				ExceptionLogger.error("BatchReportDetailController#addShowColunms",
						MessageConstants.NOT_FIND_CURRENT_USER);
				return result;
			}
			MapCache.set(userInfo.getId() + "_" + USER_DEFINED_COLUMN_KEY, columns);
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return result;
	}

	/**
	 * 
	 * @api {get} /batchDetail/batchReportDetailList.json 批量核查详情列表
	 * @apiName batchReportDetailList
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/batchReportDetailList.json")
	public RestServiceResult<List<Map<String, Object>>> batchReportDetailList(Page page, HttpServletRequest request,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "batchId", defaultValue = "", required = true) String batchId) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg(MessageConstants.SYSTEM_ERROR);
				ExceptionLogger.error("BatchReportDetailController#batchReportList",
						MessageConstants.NOT_FIND_CURRENT_USER);
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + USER_DEFINED_COLUMN_KEY);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? BatchReportDetailFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		try {
			List<Map<String, Object>> data = batchReportDetailService.getBatchReportDetailByConditionForPage(
					showColumns, new String[] { "id", "batchId","tybm" }, condition, page, batchId);
			result.setCount(page.getTotalCount());
			result.setData(data);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("列表数据查询异常，请稍后再试");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchDetail/download.json 批量核查报告下载
	 * @apiName download
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiParam {Integer} id 报告详情编号
	 * @apiParamExample {json} 请求参数示例 {"id":1}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/download.json")
	public RestServiceResult<Object> download(HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "", required = true) Integer id) {
		try {
			return batchReportDetailService.download(absolutepath, id, response);
		} catch (Exception e) {
			ExceptionLogger.error("BatchReportDetailController#download", "批量核查报告下载异常！ERROR：" + e.getMessage(), e);
			RestServiceResult<Object> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("批量核查报告下载异常，请稍后再试");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchDetail/preview.json 批量核查报告预览
	 * @apiName preview
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiParam {Integer} id 核查详情ID
	 * @apiParamExample {json} 请求参数示例 {"id":1}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/preview.json")
	public RestServiceResult<Object> preview(HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "", required = true) Integer id) {
		try {
			return batchReportDetailService.preview(absolutepath, id, response);
		} catch (Exception e) {
			ExceptionLogger.error("BatchReportDetailController#preview", "批量核查报告预览异常！ERROR：" + e.getMessage(), e);
			RestServiceResult<Object> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("批量核查报告预览异常，请稍后再试");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchDetail/getReports.json 选择性下载批量核查报告
	 * @apiName getReports
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiParam {String} filePath 文件地址
	 * @apiParamExample {json} 请求参数示例 {"filePath":"C:/a.zip"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/getReports.json")
	public RestServiceResult<Object> getReports(HttpServletResponse response,
			@RequestParam(value = "filePath", defaultValue = "", required = true) String filePath) {
		if (StringUtils.isBlank(filePath)) {
			RestServiceResult<Object> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("压缩包损坏，重新生成");
			return result;
		}
		try {
			return batchReportDetailService.getReports(filePath, response, "批量核查");
		} catch (Exception e) {
			ExceptionLogger.error("BatchReportDetailController#getReports", "下载批量核查报告异常！ERROR：" + e.getMessage(), e);
			RestServiceResult<Object> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("下载批量核查报告异常，请稍后再试");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchDetail/checkReports.json 校验下载文件
	 * @apiName checkReports
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiParam {String} id 编号
	 * @apiParam {String} batchId 批次ID
	 * @apiParamExample {json} 请求参数示例 {"id":"1,2","batchId":"1"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/checkReports.json")
	public RestServiceResult<String> checkReports(
			@RequestParam(value = "id", defaultValue = "", required = true) String id,
			@RequestParam(value = "batchId", defaultValue = "", required = true) String batchId) {
		if (StringUtils.isBlank(id)) {
			RestServiceResult<String> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("请选择需要下载报告的企业");
			return result;
		}
		try {
			return batchReportDetailService.checkReports(absolutepath, batchId, StringUtils.split(id, ","));
		} catch (Exception e) {
			ExceptionLogger.error("BatchReportDetailController#checkReports", "下载批量核查报告异常！ERROR：" + e.getMessage(), e);
			RestServiceResult<String> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("下载批量核查报告异常，请稍后再试");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchDetail/export.json 批量核查详情导出
	 * @apiName exportData
	 * @apiVersion 0.0.1
	 * @apiGroup
	 * @apiParam {String} batchId 批次ID
	 * @apiParamExample {json} 请求参数示例 {"batchId":"1"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/export.json")
	public RestServiceResult<List<Map<String, Object>>> exportData(
			@RequestParam(value = "batchId", defaultValue = "", required = true) String batchId,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
			HttpServletResponse response, HttpServletRequest request) {
		page.setLimit(1000);
		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		List<OptionalColumn> optionalColumns = BatchReportDetailFieldsEnum.getOptionalColumns();
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<>();
		// 获取当前用户信息
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg(MessageConstants.SYSTEM_ERROR);
				ExceptionLogger.error("BatchReportDetailController#exportData", MessageConstants.NOT_FIND_CURRENT_USER);
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			List<Map<String, Object>> data = batchReportDetailService.getBatchReportDetailByConditionForPage(
					showColumns, new String[] { "id", "batchId" }, condition, page, batchId);
			ExcelUtil.downloadExcel(response, data, batchId + "批量核查详情", batchId, showColumns, optionalColumns);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("批量核查详情导出异常，请稍后再试");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchDetail/reCreateReport.json 报告重新生成
	 * @apiName reCreateReport
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiParam {Integer} id 报告详情ID
	 * @apiParamExample {json} 请求参数示例 {"id":1}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/reCreateReport.json")
	public RestServiceResult<Object> reCreateReport(
			@RequestParam(value = "id", defaultValue = "", required = true) Integer id) {
		try {
			return batchReportDetailService.reCreateReport(absolutepath, pdfJsPath, pdfPagePath, googlePath, "100000",
					id);
		} catch (Exception e) {
			ExceptionLogger.error("BatchReportDetailController#reCreateReport", "报告重新生成异常！ERROR：" + e.getMessage(), e);
			RestServiceResult<Object> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("报告重新生成异常，请稍后再试");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchDetail/fileExist.json 报告是否存在
	 * @apiName fileExist
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiParam {Integer} id 批量核查详情ID
	 * @apiParamExample {json} 请求参数示例 {"id":1}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/fileExist.json")
	public RestServiceResult<Object> fileExist(
			@RequestParam(value = "id", defaultValue = "", required = true) Integer id) {
		try {
			return batchReportDetailService.fileExist(absolutepath, id);
		} catch (Exception e) {
			ExceptionLogger.error("BatchReportDetailController#fileExist", "报告下载异常！ERROR：" + e.getMessage(), e);
			RestServiceResult<Object> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("报告下载异常，请稍后再试");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchDetail/filesExist.json 批量下载报告是否存在
	 * @apiName filesExist
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiParam {String} id ID集合
	 * @apiParam {String} batchId 批次ID
	 * @apiParamExample {json} 请求参数示例 {"id":"1,2","batchId":"BR1"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping("/filesExist.json")
	public RestServiceResult<Object> filesExist(
			@RequestParam(value = "id", defaultValue = "", required = true) String id,
			@RequestParam(value = "batchId", defaultValue = "", required = true) String batchId) {
		if (StringUtils.isBlank(id)) {
			RestServiceResult<Object> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("请选择需要下载报告的企业");
			return result;
		}
		try {
			return batchReportDetailService.filesExist(absolutepath, batchId, StringUtils.split(id, ","));
		} catch (Exception e) {
			ExceptionLogger.error("BatchReportDetailController#filesExist", "报告下载异常！ERROR：" + e.getMessage(), e);
			RestServiceResult<Object> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("报告下载异常，请稍后再试");
			return result;
		}
	}
}
